<template>
  <div class="rule-base innerPageTable-out-flex">
    <search-form
      :form-data="formData"
      @search="searchHandle"
      @reset="resetHandle"
    ></search-form>
    <InnerPageTable ref="listTable" :config="pageTableConfig" >
          <div slot="table-bar">
              <RPButton optType="create" @click="addHandler()" />
<!--              <Button  @click.native="importHandle">导入</Button>-->
              <input type="file" ref="selectFile" style="display:none" @change="importDatas($event,'rule/bpmn/import')" />
              <Button  @click.native="exportHandle">导出</Button>
<!--              <Button @click.native="dowloadHandle">下载模板</Button>-->
              <Button type="error" @click.native="deleteHandle">删除</Button>
              <Button v-show="false"></Button>
          </div>
    </InnerPageTable>
  </div>
</template>
<script>
import SearchForm from "@/components/common/SearchForm"
import ruleDetails from "./pages/RuleDetails";

import { generateLists,configForm } from "./columns.js";
import ruleBaseAPI from "@/api/ruleBaseApi.js";
import { mixin } from './mix/mixin'
// import { mapState } from "vuex";
// import state from "@/tools/state";

export default {
  name: 'rule-base',
  mixins: [mixin],
  components: {
    searchForm: SearchForm,
    ruleDetails :ruleDetails
  },

  computed: {
    // ...mapState('sasspWeb', state),
    searchData() {
      return configForm.bind(this)()
    }
  },

  data () {
    return {
      // formData:formData,
      pageTableConfig: {
        loadDataFn: this.getTableList,
        columns: generateLists.bind(this)(),
        autoFirst: true,
        selectionAreaItem: { key: "id", title: "userName" },
        allSelection: [],
        onSelectionChange: this.selectHandle,
        initParam: {
          "bpmnStateList": [],
          "code": "",
          "codeList": [],
          "dataItemName": "",
          "dataSubject": "",
          "describes": "",
          "functionModules": "",
          "idList": [],
          "profitCenterList": [],
          "stateList": [],
          "title": "",
          "descs": ["create_time"]
        }
      },
      codeInt: '',//初始化编码
      idInt:''//初始化ID
    }
  },

  //外部引入的URL时，路由打开详情页
  activated() {
    if (this.$route.query.id) {
      this.detailHandle({ id: this.$route.query.id, code: '' })
    }
    this.searchHandle()
  },

  methods: {
    //获取表格数据
    getTableList(tableObj) {
      let { responseProcess, initParam, param } = tableObj;
      const params = {
        ...param,
        ...initParam
      }
      ruleBaseAPI.querylist(params).then(res => {
        responseProcess(res.data);
      })
    },

    //新建事件
    async addHandler() {
      //新建页面生成编码和ID
      const params = {"prefix": "RG"}
      //初始化编码
      const codeData =  await ruleBaseAPI.buildCode(params)
      this.codeInt = codeData.data
      //初始化ID
      const idData =  await ruleBaseAPI.buildId()
      this.idInt = idData.data
      new this.$sidelipPage(
        ruleDetails,
        { props: { idInt: this.idInt, codeInt: this.codeInt, title: '新建信息', route: 'rule-base' } ,isNav: false },
        //关闭 pageModal 的回调
        () => {
          this.resetHandle()
        }
      );
    },

    //详情事件按钮
    detailHandle(row) {
      let rowDetail ={}
      let detailId = row.id
      let groupCode = row.code
      let isDisabled = false
      // 查询
      let params={
        "codeList": [],
        "dataItemName": "",
        "dataSubject": "",
        "describes": "",
        "functionModules": "",
        "idList": [],
        "stateList": [],
        "title": ""
      }
      params.idList.push(detailId)
      ruleBaseAPI.queryList1(params).then(res => {
        rowDetail = res.data[0]
        if (rowDetail.bpmnState) {
          new this.$sidelipPage(ruleDetails,
            { props: { rowDetail, detailId, groupCode, bpmnState: rowDetail.bpmnState, isDisabled, title: '详情信息(只读)', route: 'rule-base' },isNav: false  },
            () => {
              // 关闭时的回调
              // this.resetHandle()
              this.searchHandle()
            }
          );
        } else {
          new this.$sidelipPage(
            ruleDetails,
            { props: { rowDetail, detailId, groupCode, title: '详情信息', route: 'rule-base' },isNav: false  },
            () => {
              // 关闭时的回调
              this.searchHandle()
            }
          );
        }
      })


    },

    //下载模板事件
    dowloadHandle() {
      ruleBaseAPI.downloadData().then(response => {
        let excelName = decodeURI(response.headers['content-disposition'].split(";")[1].split("=")[1]);//截取响应头的文件后缀
        // console.log(excelName ,'截取的文件名');
        const link = document.createElement("a");//创建a标签
        let blob = new Blob([response.data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf - 8"
        });//设置文件类型
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);//将文件流转化为blob地址
        link.setAttribute("download", excelName);//文件名，而不是写死.excel之类
        // link.download = excelName
        document.body.appendChild(link);//创建
        link.click();//点击事件
        document.body.removeChild(link);//移除

      }).catch(err => {
      })
    },
    //导入事件
    importHandle(file) {
      this.$refs.selectFile.click();
    },

    checkFileType: function(fileType) {
      const acceptTypes = ["xls", "xlsx"];
      for (var i = 0; i < acceptTypes.length; i++) {
        if (fileType === acceptTypes[i]) {
          return true;
        }
      }
      return false;
    },
    importDatas(e,url) {
      const inputCom = e.target;
      const files = inputCom.files;
      let param = new FormData();
      [].forEach.call(files, file => {
        if (!this.checkFileType(file.name.split(".").pop())) {
          this.$message.error({
            content: "仅支持导入excel 文件",
            duration: 3
          });
          return false;
        } else {
          param.append("file", file);
        }
      });
      if (param.get("file")) {
        //添加请求头
        let config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        };
        this.showUploading();
        e.target.value = ''
        ruleBaseAPI.importData(param, url)
          .then(response => {
            this.hideUploading();
            this.searchHandle()  ///刷新 数据
          })
          .catch((err) => {
            // inputCom.value = "";
            console.error(err)
            this.hideUploading();
          });
      }
    },
    hideUploading() {
      this.$Spin.hide();
    },
    showUploading() {
      this.$Spin.show({
        render: h => {
          return h("div", [
            h("Icon", {
              class: "demo-spin-icon-load",
              props: {
                type: "ios-loading",
                size: 18
              }
            }),
            h("div", "上传中")
          ]);
        }
      });
    },
    //导出事件
    exportHandle() {
      let params = {
        "codeList": [],
        "dataItemName": "",
        "dataSubject": "",
        "describes": "",
        "functionModules": "",
        "idList": [],
        "stateList": [],
        "title": ""
      }
      let allSelected = this.$refs["listTable"].allSelection;
      const idList = allSelected.map(user => user.id);
      params.idList=idList
      if (allSelected.length == 0) {
        this.$message.error(this.$t("请至少选择一条数据"));
        return;
      }
      ruleBaseAPI.exportData(params).then(response => {
        let excelName = decodeURI(response.headers['content-disposition'].split(";")[1].split("=")[1]);//截取响应头的文件后缀
        // console.log(excelName ,'截取的文件名+++');
        const link = document.createElement("a");//创建a标签
        let blob = new Blob([response.data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf - 8"
        });//设置文件类型
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);//将文件流转化为blob地址
        link.setAttribute("download", excelName);//文件名，而不是写死.excel之类
        // link.download = excelName
        document.body.appendChild(link);//创建
        link.click();//点击事件
        document.body.removeChild(link);//移除
        this.$refs["listTable"].allSelection = [];
            // this.searchHandle()
        this.searchHandle()
      }).catch(err => {})

    },
    //删除事件
    // deleteHandle() {
    //   let allSelected = this.$refs["listTable"].allSelection;
    //   if (allSelected.length == 0) {
    //     this.$message.error(this.$t("请至少选择一条数据"));
    //     return;
    //   }
    //   this.$confirm
    //     .warning(this.$t("确定删除后，无法恢复！"))
    //     .then(() => {
    //       const idList = allSelected.map(user => user.id);
    //       ruleBaseAPI.deleteData({idList}).then(res => {
    //         this.$message.success({
    //           content: this.$t("删除成功"),
    //           duration: 3
    //         });
    //         this.$refs["listTable"].allSelection = [];
    //         this.searchHandle()
    //       });

    //     }).catch(_ => _);
    // }
  }

}
</script>
